var history_data = function(){
	var params = {};
	return {
		
		/**
		 * 页面初始化调用方法
		 * @param clientId 终端id
		 * @param packCode 电池唯一序列号
		 */
		init: function(clientId, packCode){
			//初始化查询条件
			history_data.setDefaultQuery();
			//初始化表格数据
			history_data.historyDataTableInit(packCode,clientId);
			$("#packDetail").hide();
			// 查询
			$("#btn_query").click(function(e) {
				var table = $('#pack_monitor_history_table').DataTable();
				table.draw(true);
				$("#packDetail").hide();
			});
		    // 重置
			$("#btn_reset").click(function() {
				history_data.setDefaultQuery();
			});
			//enter查询
			$(function(){
				$('.enterSearch').bind('keyup', function(event) {
					if (event.keyCode == "13") {
						//回车执行查询
						$('#btn_query').click();
					}
				});
			});
			
			//切换tab echart
			$('.nav-tabs a[href="#tab_1_1"]').on('shown.bs.tab', function(e){
				if(params){
					history_data.setEchartData(params);
				}
				
			});
			//切换tab 位置监控
			$('.nav-tabs a[href="#tab_1_2"]').on('shown.bs.tab', function(e){
					history_data.setMonitorLocation(params);
			});
			
			//切换tab 位置历史
			$('.nav-tabs a[href="#tab_1_3"]').on('shown.bs.tab', function(e){
				$('#history_location_table').DataTable().destroy();
				history_data.setHistoryLocation(params);
			});
			
			//切换tab 历史监控
			$('.nav-tabs a[href="#tab_1_4"]').on('shown.bs.tab', function(e){
				$('#history_warning_table').DataTable().destroy();
				history_data.setHistoryWarning(clientId, packCode);
			});
			
		},
		setDefaultQuery:function(){
			Date.prototype.Format = function (fmt) { //author: meizz 
			    var o = {
			        "M+": this.getMonth() + 1, //月份 
			        "d+": this.getDate(), //日 
			        "h+": this.getHours(), //小时 
			        "m+": this.getMinutes(), //分 
			        "s+": this.getSeconds(), //秒 
			        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
			        "S": this.getMilliseconds() //毫秒 
			    };
			    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
			    for (var k in o)
			    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
			    return fmt;
			};
			
			$("#startTime").val((new Date().Format("yyyy-MM-dd hh:mm:ss")).substring(0,11)+"00:00:00");
			$("#endTime").val(new Date().Format("yyyy-MM-dd hh:mm:ss"));
			
		},
		/**
		 * 根据点击行显示详情
		 * @param g 采集时间
		 * @param p 电池唯一id
		 * @param c 终端唯一id
		 */
		showDetail:function(g,p,c){
			params['gatherTime'] = g;
			params['packCode'] =p;
			params['colClientId'] = c;
		  	history_data.setPackInfo(params);
	    	  //加载tab数据
	    	$(".tab-pane").each(function(){
					if($(this).hasClass("active")){
						switch($(this).attr('id'))
						{
							case "tab_1_1":
								history_data.setEchartData(params);
							  break;
							case "tab_1_2":
								history_data.setMonitorLocation(params);
							  break;
							case "tab_1_3":
								$('#history_location_table').DataTable().destroy();
								history_data.setHistoryLocation(params);
								  break;
							case "tab_1_4":
								history_data.setHistoryWarning(clientId, packCode);
								break;
							default:
								history_data.setEchartData(params);
						}
					}
				});
		},
		/**
		 * 历史轨迹
		 * @param d 终端id+电池唯一序列号+采集时间
		 */
		setHistoryLocation:function(d){
			//导出数据
		  $("#locaion_history_box").empty();//清空地图内容
			    var map = new BMap.Map("locaion_history_box");
				map.centerAndZoom(new BMap.Point(116.417854,39.921988),5);//默认中心点
				map.enableScrollWheelZoom(true);//缩放
				//向地图中添加缩放控件  
          //向地图中添加缩略图控件  
          var ctrlOve = new window.BMap.OverviewMapControl({  
              anchor: BMAP_ANCHOR_BOTTOM_RIGHT,  
              isOpen: 1  
          });  
          map.addControl(ctrlOve);
          //向地图中添加比例尺控件  
          var ctrlSca = new window.BMap.ScaleControl({  
              anchor: BMAP_ANCHOR_BOTTOM_LEFT  
          });  
          map.addControl(ctrlSca); 
          var start_circle = new BMap.Symbol(BMap_Symbol_SHAPE_CIRCLE, {
			    scale: 5.0,
			    strokeWeight: 1.5,
			    fillColor: 'blue',
			    fillOpacity: 1.0
          });
          var circle = new BMap.Symbol(BMap_Symbol_SHAPE_CIRCLE, {
			    scale: 5.0,
			    strokeWeight: 1.5,
			    fillColor: 'red',
			    fillOpacity: 1.0
          });
          //添加地图自定义控件
          function selectTime(){
        	  this.defaultAnchor = BMAP_ANCHOR_TOP_LEFT;
              this.defaultOffset = new BMap.Size(10, 10); // 距离左上角位置
              this.searchBox = document.createElement("input");// 搜索框
              this.searchBox.setAttribute("type", "text"); 
          }
          // 通过JavaScript的prototype属性继承于BMap.Control
          selectTime.prototype = new BMap.Control();
          // 自定义控件必须实现自己的initialize方法,并且将控件的DOM元素返回
          // 在本方法中创建个div元素作为控件的容器,并将其添加到地图容器中
          selectTime.prototype.initialize = function(map){
            // 创建一个DOM元素
            var div = document.createElement("div");
            // 设置样式
            
            var txt = this.searchBox;
            txt.className = "form-control";
            txt.setAttribute("id", "selectHistoryLocationTime");
            div.appendChild(txt);
            // 添加DOM元素到地图中
            map.getContainer().appendChild(div);
            // 将DOM元素返回
            return div;
          };
          // 创建控件
          var selectTimeCtrl = new selectTime();
          // 添加到地图当中
          map.addControl(selectTimeCtrl);
          
          $('#selectHistoryLocationTime').daterangepicker({
  			"timePicker": true,
  			"timePicker24Hour": true,
  			"timePickerSeconds":true,  //精确到秒
  			"locale": {
  				"format": "YYYY-MM-DD HH:mm:ss",
  				"separator": " - ",
  				"applyLabel": "确定",
  				"cancelLabel": "取消",
  				"firstDay": 1
  			},
  			"dateLimit" : {
				days : 2 //限定两天内
			}
		  }, function(start, end, label) {
        	  //console.log(start.format("YYYY-MM-DD HH:mm:ss"), end.format("YYYY-MM-DD HH:mm:ss"));
          });
          
          //日期选择框赋初值
          $('#selectHistoryLocationTime').data('daterangepicker').setStartDate((util.getDateStr(d.gatherTime)).substring(0,11)+"00:00:00");
          $('#selectHistoryLocationTime').data('daterangepicker').setEndDate(util.getDateStr(d.gatherTime));
          //点击事件
          $('#selectHistoryLocationTime').on('apply.daterangepicker',function(ev, picker) {
        	  $('#history_location_table').DataTable().draw(true);
          });
          //取消事件
          $('#daterange').on('cancel.daterangepicker',function(ev, picker) {
        	  $('#selectHistoryLocationTime').data('daterangepicker').setStartDate((util.getDateStr(d.gatherTime)).substring(0,11)+"00:00:00");
              $('#selectHistoryLocationTime').data('daterangepicker').setEndDate(util.getDateStr(d.gatherTime));
          });
          //处理表格
			$('#history_location_table').DataTable({
				"searching": false,
				"bDestroy": true,
				"bRetrieve": true,
				"processing" : true,
				"serverSide" : true,
				"sAjaxSource" : "main/packDataMonitor/getHistoryLocationListByPage.mvc",
				"fnServerData" : queryData,
				"pageLength" : 10,
				"sDom" : "<'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
				"oLanguage" : util.getDToLanguage(),
				"columns" : [ 
				{
					"data" : "",
					"bSortable" : false,
					"visible" : false,  //隐藏列
					"defaultContent": ""
				},
				{
					"data" : "gatherTime",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "address",
					"bSortable" : false,
					"defaultContent": ""
				}
			 ]
			});
			//table查询方法
			function queryData(sSource, aoData, fnCallback) {
				App.blockUI($("#tab_1_3"));//开始loading
				aoData.push({
					"name" : "clientId",
					"value" : d.colClientId
				});
				aoData.push({
					"name" : "packCode",
					"value" : d.packCode
				});
				aoData.push({
					"name" : "gatherTimes",
					"value" : d.gatherTime
				});
				aoData.push({
					"name" : "selectTime",
					"value" : $("#selectHistoryLocationTime").val()
				});
				aoData.push({
					"name" : "flag",
					"value" : "history"
				});
				$.ajax({
					"type" : "post",
					"url" : sSource,
					"dataType" : "json",
					"data" : {
						"aoData" : JSON.stringify(aoData)
					},
					"success" : function(resp) {
						//绘制历史轨迹    resp.aaData
						setHistoryLine();
						if(resp.aaData.length>0){
							//存在数据添加导出按钮
							$("#history_toolbar").show();
						}else {
							//没有数据   移除导出按钮
							$("#history_toolbar").hide();
						}
						fnCallback(resp);
					},
					"error":function(){
						rmsBox.notify('error', {msg: '加载数据出错！'});
						App.unblockUI($("#tab_1_3"));
					}
				});
			};
			
			 //导出数据
	  	    $('#export_history').on('click',function(){
	  			Date.prototype.Format = function (fmt) { //author: meizz 
				    var o = {
				        "M+": this.getMonth() + 1, //月份 
				        "d+": this.getDate(), //日 
				        "h+": this.getHours(), //小时 
				        "m+": this.getMinutes(), //分 
				        "s+": this.getSeconds(), //秒 
				        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
				        "S": this.getMilliseconds() //毫秒 
				    };
				    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
				    for (var k in o)
				    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
				    return fmt;
				};
				var exportTime = new Date().Format("yyyyMMddhhmmss");
	  	    	var url = "main/packDataMonitor/getHistoryLocationListForTrailTwo.mvc?clientId="+d.colClientId+"&packCode="+d.packCode+"&gatherTimes="+util.getDateStr(d.gatherTime)+"&selectTime="+$("#selectHistoryLocationTime").val() + "&exportTime="+ exportTime;
	  	    	$.fileDownload(url, {
	    			httpMethod: 'POST',
	    			prepareCallback:function(url){
	    				App.blockUI($("#tab_1_3"));
	    				console.log("准备提交");
	    			},
	    			successCallback:function(url){
	    				App.unblockUI($("#tab_1_3"));
	    				console.log("操作成功");
	    			},
	    			failCallback: function (html, url) {
	    				rmsBox.notify('error', {msg: '操作失败！',delay:3000});
	    			}
	            });
	  	    	downloadExcel(exportTime+".xlsx");
			});
			
			/**
			 * 轮询检查excel是否生成
			 * @param fileName 文件名
			 */
			function downloadExcel(fileName){
	  	    	var timer = window.setInterval(function(){
		  	    		$.ajax({
							"type" : "post",
							"url" : "main/packDataMonitor/checkExcelTempExist.mvc",
							"dataType" : "json",
							"async" : false,
							"data" : {
								'fileName' : fileName
							},
							"success" : function(resp) {
								if(resp.flag == "success"){
									clearInterval(timer);
									//下载生成文件的文件
									var url = "main/packDataMonitor/downloadTrailExcel.mvc?fileName="+fileName;
						  	    	$.fileDownload(url, {
						    			httpMethod: 'POST',
						    			prepareCallback:function(url){
						    				console.log("准备提交");
						    			},
						    			successCallback:function(url){
						    				rmsBox.notify('success', {msg: '操作成功'});
						    				console.log("操作成功");
						    			},
						    			failCallback: function (html, url) {
						    				console.log(2);
						    				rmsBox.notify('error', {msg: '操作失败！',delay:3000});
						    			}
						            });
									
								}
							},
							error:function(e){
							}
						});
				},3000);
	  	    }
			
			function setHistoryLine(){
	  		  $.ajax({
					"type" : "post",
					"url" : "main/packDataMonitor/getHistoryLocationList.mvc",
					"dataType" : "json",
					"async" : false,
					"data" : {
						'clientId' : d.colClientId,
						'packCode' : d.packCode,
						'gatherTimes' : d.gatherTime,
						'selectTime' : $("#selectHistoryLocationTime").val(),
						'flag' : 'history'
						
					},
					"success" : function(resp) {
						if(resp.aaData.length>0){
							//存在数据添加导出按钮
							var points = new Array();
							for(var i = 0; i < resp.aaData.length; i++){
								points.push(new BMap.Point(parseFloat(resp.aaData[i].longitude),parseFloat(resp.aaData[i].latitude)));
								if(i == 0){
									var marker = new BMap.Marker(new BMap.Point(parseFloat(resp.aaData[i].longitude),parseFloat(resp.aaData[i].latitude)), {icon: circle});
									map.addOverlay(marker);
								}
								if( i == (resp.aaData.length - 1)){
									var marker = new BMap.Marker(new BMap.Point(parseFloat(resp.aaData[i].longitude),parseFloat(resp.aaData[i].latitude)), {icon: start_circle});
									map.addOverlay(marker);
								}
							}
							var polyline = new BMap.Polyline(
															   points, 
									                         { strokeColor:"green",//设置颜色   
					                                           strokeWeight:3, //宽度  
					                                           strokeOpacity:1
					                                           }
							                                 );//透明度  
					              map.addOverlay(polyline);  
				  	    //缩放级别自适应
						var view = map.getViewport(eval(points));  
						var mapZoom = view.zoom;   
						var centerPoint = view.center;   
						map.centerAndZoom(centerPoint,mapZoom);  
						}else {
							//清空轨迹
							map.clearOverlays();
						}
						App.unblockUI($("#tab_1_3"));
					},
					error:function(e){
						App.unblockUI($("#tab_1_3"));
						rmsBox.notify('error', {msg: '加载数据出错！'});
					}
				});
	  	    }
		},
		/**
		 * 显示监控位置信息
		 * @param d 电池唯一序列号+终端id+采集时间 
		 */
		setMonitorLocation:function(d){
			 $("#locaion_monitor_box").empty();//清空地图内容
			    var map = new BMap.Map("locaion_monitor_box");
				map.centerAndZoom(new BMap.Point(116.417854,39.921988),14);//默认中心点
				map.enableScrollWheelZoom(true);//缩放
				//向地图中添加缩放控件  
             var ctrlNav = new window.BMap.NavigationControl({  
                 anchor: BMAP_ANCHOR_TOP_LEFT,  
                 type: BMAP_NAVIGATION_CONTROL_LARGE  
             });  
             map.addControl(ctrlNav);
             //向地图中添加缩略图控件  
             var ctrlOve = new window.BMap.OverviewMapControl({  
                 anchor: BMAP_ANCHOR_BOTTOM_RIGHT,  
                 isOpen: 1  
             });  
             map.addControl(ctrlOve);
             //向地图中添加比例尺控件  
             var ctrlSca = new window.BMap.ScaleControl({  
                 anchor: BMAP_ANCHOR_BOTTOM_LEFT  
             });  
             map.addControl(ctrlSca); 
             var myIcon = new BMap.Icon("./media/image/point_icon.png", new BMap.Size(40, 45));  
             if(d){
                 //添加标注
      			$.ajax({
     				'type':'post',
     				'url':'main/packDataMonitor/getHistoryLocationInfo.mvc',
     				'dataType':'json',
     				"cache":false,
     				'async':true,
     				'data': {
     					"colClientId":d.colClientId,
     					"packCode":d.packCode,
     					"gatherTime":util.getDateStr(d.gatherTime)
     				},
     				'success':function(data){
     					//清空上次标注
     					map.clearOverlays(); 
     					if(data && data.clientId!=null){
     							var new_point = new BMap.Point(data.longitude, data.latitude);
     							var marker = new BMap.Marker(new_point, {icon:myIcon});  // 创建标注
     							var _facName = data.facName;
    							_facName = data.facName == null?'未关联厂区':data.facName;
     							var lableInfo ="<table><tr><td><b>最后采集时间：</b>"+data.gatherTime+"</td><td><b>采集终端ID：</b>"+data.clientId+"</td></tr>" +
     							"<tr><td><b>电池ID：</b>"+data.packCode+"</td><td><b>SOC：</b>" + data.soc + "</td></tr>" +
     							"<tr><td><b>总电压：</b>" + data.vol + "V</td><td><b>总电流：</b>" + data.current +"A</td></tr>" +
     							"<tr><td><b>客户：</b>" + data.cusName + "</td><td><b>所属厂区：</b>" + _facName + "</td></tr>" +
     							"<tr><td><b>地理位置：</b>"+data.address+"</td><td></td></tr>" +
     								"</table>";
     							var info = new window.BMap.InfoWindow(lableInfo);
     							marker.addEventListener("mouseover", function () {
     			                        this.openInfoWindow(info);
     			                    });
     							map.addOverlay(marker);// 将标注添加到地图中
     							map.panTo(new_point);
     					}
     					App.unblockUI($("#packDetail"));
     					
     				},
     				'error':function(msg){
     					console.log("error");
     					App.unblockUI($("#packDetail"));
     				}
     			});
             }
     
		},
		
		/**
		 * 加载echart图表数据
		 * @param d 终端id 电池唯一序列号 + 采集时间
		 * @returns
		 */
		setEchartData:function(d){
			var _maxVol = $("#MAX_VOL_VAL").text();
			_maxVol = _maxVol.substring(0, _maxVol.length-3);
			var _minVol = $("#MIN_VOL_VAL").text();
			_minVol = _minVol.substring(0, _minVol.length-3);
			if(_maxVol){
				$.ajax({
					"type" : "post",
					"url" : "main/packDataMonitor/getEchartHistoryData.mvc",
					"dataType" : "json",
					"cache":false,
					"async":true,
					"data" :  {
						"colClientId": d.colClientId,
						"packCode": d.packCode,
						"gatherTime": d.gatherTime,
						"maxVol": _maxVol,
						"minVol": _minVol
					},
					"success" : function(resp) {
						var markPoint;
						var colorList;
						if(resp.chartInfo!=null&&(resp.chartInfo.length==0)){
							rmsBox.notify('warning', {msg: '无单体电压和监测点温度数据！',delay:2000});
						}
						if(resp.chartInfo != null){
							//处理表格
							$("#minitor_pack_chart").empty();
							$.each(resp.chartInfo, function(i, item){
								//温度
								var temp = "";
								$.each(item.temp,function(k, te){
									temp += te.temp+"、";
								});
								if(temp){
									temp = temp.substring(0,temp.length-1);
								}
								//动态创建表格
								var chartHtml = "";
								chartHtml += '<li> <div class="echarts-title"> ';
								chartHtml += '<span class = "c-bold">第'+item.no+'组</span>';
								chartHtml += '&nbsp;&nbsp;&nbsp;温度监测点单体序号/温度(℃)：';
								chartHtml += '<span class="c-red">'+temp+'</span>';
								chartHtml += '</div>';
								if(item.vol){
									chartHtml += '<div id="chart_'+i+'"class="echats"></div>';
								}
								$("#minitor_pack_chart").append(chartHtml);
								//调用echart
								if(item.vol){
									// item.markpoint 峰值标志位 11：高压报警&&低压报警 10：高压报警 01：低压报警 00：没有报警
									/*if ("11"==item.markpoint) {
										//既有高压报警 又有低压报警
										markPoint = [{
												type : 'max',
												name : '最大值',
												itemStyle : {
													normal : {
														color : '#000'
													}
												}
											}, {
												type : 'min',
												name : '最小值',
												itemStyle : {
													normal : {
														color : '#000'
													}
												}
											}
										];
										colorList = ['#E02222', '#FFFF00', '#57B5E3'];
									} else if ("10"==item.markpoint) {
										//只有高压报警
										markPoint = [{
												type : 'max',
												name : '最大值',
												itemStyle : {
													normal : {
														color : '#000'
													}
												}
											}
										];
										colorList = ['#E02222', '#57B5E3', '#57B5E3'];
									} else if ("01"==item.markpoint) {
										//只有低压报警
										markPoint = [{
												type : 'min',
												name : '最小值',
												itemStyle : {
													normal : {
														color : '#000'
													}
												}
											}
										];
										colorList = ['#57B5E3', '#FFFF00', '#57B5E3'];
									} else {
										//不存在告警
										markPoint = null;
										colorList = ['#57B5E3', '#57B5E3', '#57B5E3']
									}*/
									markPoint = [{
										type: 'max',
										name: '最大值',
										itemStyle: {
											normal: {
												color: '#E02222'
											}
										}
									}, {
										type: 'min',
										name: '最小值',
										itemStyle: {
											normal: {
												color: '#000'
											}
										}
									}];
									colorList = ['#E02222', '#FFFF00', '#57B5E3'];
									setTimeout(function(){
										history_data.EconfigAPI(item,"chart_"+i, markPoint, colorList);
									},500);
									
								}
							});
						}
						App.unblockUI($("#packDetail"));//停止loading
					},
					error:function(e){
						App.unblockUI($("#packDetail"));//停止loading
						rmsBox.notify('error', {msg: '出错了！',delay:3000});
					}
				});
			} else {
				$("#minitor_pack_chart").empty();
			}
		},
		
		setHistoryWarning : function(c, p) {
			var tableId = 'history_warning_table';
			util.initCheckBox(tableId);
			var checkBoxDivStr = '<div class="checker" onclick="util.selectCheckBox(\'' + tableId + '\', this)"><span><input type="checkbox" class="checkboxes"></span></div>';			
			//table查询方法
			function queryData(sSource, aoData, fnCallback) {
				aoData.push({
					"name" : "clientId",
					"value" : c
				});
				aoData.push({
					"name" : "packCode",
					"value" : p
				});
				$.ajax({
					"type" : "get",
					"contentType" : "application/json",
					"url" : sSource,
					"dataType" : "json",
					"data" : {
						"aoData" : JSON.stringify(aoData)
					},
					"success" : function(resp) {
						fnCallback(resp);
					}
				});
			};
	         //处理表格
			$('#history_warning_table').DataTable({
				"bInfo": true,//页脚信息
				"bDestroy": true,
				"bRetrieve": true,
				"processing" : false,
				"serverSide" : true,
				"pageLength" : 10,
				"oLanguage" : util.getDToLanguage(),
				"sAjaxSource" : "main/packDataMonitor/getHistoryWarningList.mvc",
				"fnServerData" : queryData,
				"sDom" : "<'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
				"columns" : [
				{
					"data" : "pkId",
					"render" : function(data, type, full, meta) {
						 return checkBoxDivStr;
					},
					"bSortable" : false
				},
				{
					"data" : "handleStatus",
					"bSortable" : false,
					"defaultContent": "",
					"render" : function(data,type,full,meta) {
						if("已处理"==data){
							return "<span class=\"label\">"+data+"</span>";
						}else if("未处理"==data){
							return "<span class=\"label label-important\">"+data+"</span>";
						} else if ("无需处理"==data) {
							return "<span class=\"label label-warning\">"+data+"</span>";
						}
					}
				},
				{
					"data" : "alertCategory",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "happenTime",
					"bSortable" : false,
					"defaultContent": "",
					"render" : function(data, type, full, meta) {
						if(data){
						   return util.getDateStr(data);
						}
					}
				},
				{
					"data" : "alertCode",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "updateDate",
					"bSortable" : false,
					"defaultContent": "",
					"render" : function(data, type, full, meta) {
						if(data){
						   return util.getDateStr(data);
						}
					}
				},
				{
					"data" : "",
					"bSortable" : false,
					"render" : function(data, type, full, meta) {
						if(full.zipOrigmsgPath) {
							return "<a href='javascript:;' onclick='history_data.downloadDatagram(\"" + full.pkId + "\")' class='c-blue c-line'>下载报文</a>";
						} else if(full.handleStatus=='未处理') {
							return "<a href='javascript:;' onclick='history_data.dataBack(\"" + full.pkId + "\")' class='c-blue c-line'>数据回传</a>";
						}
					},
					"defaultContent": ""
				}
			 ],
			 "fnDrawCallback" : function(oSetting) {
				util.clearSelected(tableId);
			 }
			});
			$("table#history_warning_table").find("th").eq(0).addClass("sorting_asc_disabled");
			//清除按钮绑定样式
			$('#set_handled, #set_unneed_handled').off("click");
			$("#_confirmModal").off( "click", "#set_handled_conf");
			$("#_confirmModal").off( "click", "#set_unneed_conf");
			//点击标记处理
			$("#set_handled").click(function(e){
				var d = [];
				d = util.getCheckedData("history_warning_table");
				if (d.length ==0 ) {
					util.showModal("#_alertModal", "请选择要操作的记录！");
					return false;
				} else {
					//检查所选择数据状态
					var idArray=[];
					for (var i=0;i<d.length;i++) {
						idArray.push(d[i].pkId);
					}
					$.ajax({
						"type" : "post",
						"url" : "main/packDataMonitor/checkUnhandled.mvc",
						"dataType" : "json",
						"async":false,
						"data" : {
							"ids" : idArray.join(",")
						},
						"success" : function(resp) {
							if (resp == true) {
								util.showModal("#_confirmModal", "你确定要标记已处理？", "set_handled_conf");
							} else {
								util.showModal("#_alertModal", "所选记录包含已处理或数据未回传的记录，请重新选择！");
							}
						}
					});
				}
			});
			
			//置为已处理
			$("#_confirmModal").on('click', '#set_handled_conf', function() {
				var d = [];
				d = util.getCheckedData("history_warning_table");
				var idArray = new Array();
				for (var i = 0;i<d.length;i++) {
					idArray.push(d[i].pkId);
				}
				$.ajax({
					"type" : "post",
					"url" : "main/packDataMonitor/setAlertHandled.mvc",
					"dataType" : "json",
					"data" : {
						"ids" : idArray.join(","),
						"handleType" : "handled"
					},
					"success" : function(resp) {
						if (resp.msg==true) {
							rmsBox.notify('success', {msg: '操作成功！'});
							var table = $('#history_warning_table').DataTable();
							table.draw(true);
						} else {
							rmsBox.notify('error', {msg: '数据异常！'});
						}
					},
					"error" : function() {
						rmsBox.notify('error', {msg: '数据异常！'});
					}
				});
			});
			
			//点击无需处理
			$("#set_unneed_handled").click(function(e) {
				var d = [];
				d = util.getCheckedData("history_warning_table");
				if (d.length ==0 ) {
					util.showModal("#_alertModal", "请选择要操作的记录！");
					return false;
				} else {
					//检查所选择数据状态
					var d = [];
					d = util.getCheckedData("history_warning_table");
					var idArray=[];
					for (var i=0;i<d.length;i++) {
						idArray.push(d[i].pkId);
					}
					$.ajax({
						"type" : "post",
						"url" : "main/packDataMonitor/checkUnneedhandled.mvc",
						"dataType" : "json",
						"async":false,
						"data" : {
							"ids" : idArray.join(",")
						},
						"success" : function(resp) {
							if(resp==true){
								util.showModal("#_confirmModal", "你确定要置为无需处理？", "set_unneed_conf");
							}else{
								util.showModal("#_alertModal", "所选记录包含已处理或数据已回传的记录，请重新选择！");
							}
						}
					});
				}
			});
			
			//置为无需处理
			$("#_confirmModal").on('click', '#set_unneed_conf', function() {
				var d = [];
				d = util.getCheckedData("history_warning_table");
				var packIds = new Array();
				for (var i = 0;i<d.length;i++) {
					packIds.push(d[i].pkId);
				}
				$.ajax({
					"type" : "post",
					"url" : "main/packDataMonitor/setAlertHandled.mvc",
					"dataType" : "json",
					"data" : {
						"ids" : packIds.join(","),
						"handleType" : "unneed"
					},
					"success" : function(resp) {
						if (resp.msg==true) {
							rmsBox.notify('success', {msg: '操作成功！'});
							var table = $('#history_warning_table').DataTable();
							table.draw(true);
						} else {
							rmsBox.notify('error', {msg: '数据异常！'});
						}
					},
					"error" : function() {
						rmsBox.notify('error', {msg: '数据异常！'});
					}
				});
			});
		},
		/**
		 * 配置echart 绘制电池电压电流图表
		 * @param data 数据
		 * @param elem divID
		 */
		EconfigAPI:function(data, elem, m, co) {
			//--- 折柱 ---
			var myChart = echarts.init(document.getElementById(elem));
			myChart.setOption({
				tooltip : {
					trigger : 'axis',
					formatter:"{b}<br/>{a} : {c}V"
				},
				calculable : true,
				xAxis : [{
						type : 'category',
						data : data.groupNo
					}
				],
				yAxis : [{
						type : 'value',
						scale : false,
						axisLabel : {
			                formatter: function (data) {
			                    return data + ' V';
			                }
			            }
					}
				],
				series : [{
						name : '电压',
						type : 'bar',
						data : (function (){
			                var res = [];
			                for(var i = 0; i< data.vol.length;i++){
			                	res.push(data.vol[i].toFixed(3));
			                }
			                return res;
			            })(),
					    markPoint : {
			                data : m
			            },
			            itemStyle: {
			            	normal: {
			            		color: function(params){
			            			//最大值置为红色#E02222 最小值#0D638F 中间值 '#57B5E3'
			            			/*var myData = data.vol;
			            			function compare(value1, value2) { //数字排序的函数参数
										if (value1 < value2) { //小于，返回负数
											return -1;
										} else if (value1 > value2) { //大于，返回正数
											return 1;
										} else { //其他，返回0
											return 0;
										}
									}
									myData.sort(compare);
									if(params.data == myData[myData.length-1]){
										return co[0];
									} else if (params.data == myData[0]){
										return co[1];
									} else {
										return co[2];
									}*/
									if(params.data > data.maxVol){
										return "#E02222";
									}else if(params.data <data.minVol) {
										return "#FFFF00";
									}else {
										return "#57B5E3";
									}
					            }
			            	}
			            }
					}]
			});
		},
		/**
		 * 监控电池历史详情赋值
		 * @param d 终端唯一编码+电池唯一序列号+采集时间
		 */
		setPackInfo : function(d){
			//history_data.showClientInfoPanel();
			App.blockUI($("#packDetail"));//开始loading
			//查询电池详情并赋值
			$.ajax({
				"type" : "post",
				"url" : "main/packDataMonitor/getPackHistoryDataDetail.mvc",
				"dataType" : "json",
				'async':true,
				"cache":false,
				"data" : {
					"colClientId":d.colClientId,
					"packCode":d.packCode,
					"gatherTime":d.gatherTime
				},
				"success" : function(resp) {
					if(resp.packInfo != null){
						$("#packDetail").show();
						//处理详情
						    var _packInfo = resp.packInfo;
							$("#NETWORK_STANDARD").text(resp.packInfo.NETWORK_STANDARD);
							$("#CARRIER").text(resp.packInfo.CARRIER);
							$("#SIM_PHONENO").text(resp.packInfo.SIM_PHONENO);
							$("#GPS_SIG").text(resp.packInfo.GPS_SIG);
							$("#GPRS_SIG").text(resp.packInfo.GPRS_SIG);
							//history_data.setSign("div_gps_sign", Math.ceil((parseInt(resp.packInfo.GPS_SIG) + 1)/3));
							//history_data.setSign("div_gprs_sign", Math.ceil(parseInt(resp.packInfo.GPRS_SIG)/7));
							//
							//加载gps,gprs动画
							var gps = $('#gps');
							var gpsNum = $('#gpsNum');
							var gprs = $('#gprs');
							var gprsNum = $('#gprsNum');
							gps.text(resp.packInfo.GPS_SIG);
							gpsNum.animate({width: (resp.packInfo.GPS_SIG)*48/15},1000);
							gprs.text(resp.packInfo.GPRS_SIG);
							gprsNum.animate({width: resp.packInfo.GPRS_SIG*48/35},1000);
							
							$("#PACK_CODE").text(resp.packInfo.PACK_CODE);
							$("#GATHER_TIME").text(resp.packInfo.GATHER_TIME);
							$("#RUN_TIME_SPAN").text(resp.packInfo.RUN_TIME_SPAN);
							$("#FAC_NAME").text(resp.packInfo.FAC_NAME);
							
							$("#EL_VOL").text(resp.packInfo.EL_VOL);
							$("#EL_CURRENT").text(resp.packInfo.EL_CURRENT);
							//history_data.setSocCanvas(resp.packInfo.SOC);
							
							var  batteryCapacity = $('#battery-capacity');
							batteryCapacity.animate({height: resp.packInfo.SOC*190/100},1000);
							batteryCapacity.find('span').text(resp.packInfo.SOC+"%");
							
							$("#SOC").text(resp.packInfo.SOC+"%");
							$("#MAX_VOL_VAL").text(resp.packInfo.MAX_VOL_VAL);
							$("#MIN_VOL_VAL").text(resp.packInfo.MIN_VOL_VAL);
							$("#MAX_TEMP_VAL").text(resp.packInfo.MAX_TEMP_VAL);
							history_data.setTempCanvas("chart", (resp.packInfo.MAX_TEMP_VAL).substring(0, (resp.packInfo.MAX_TEMP_VAL).length -3));
							$("#MIN_TEMP_VAL").text(resp.packInfo.MIN_TEMP_VAL);
							$("#MIN_TEMP_VAL").text(resp.packInfo.MIN_TEMP_VAL);
							$("#POWER_ON_STATUS").text(resp.packInfo.POWER_ON_STATUS);
							$("#RUN_STATUS").text(resp.packInfo.RUN_STATUS);
							
							/*
							 * 终端信息
							 */
							$("#CUS_NAME").text(resp.packInfo.CUS_NAME);
							$("#COL_CLIENT_ID").text(resp.packInfo.COL_CLIENT_ID);
							$("#IMSI").text(resp.packInfo.IMSI);
							$("#GPS_NUM").text(resp.packInfo.GPS_NUM);
							$("#PACK_MODEL").text(resp.packInfo.PACK_MODEL);
							$("#ADDRESS").text(resp.packInfo.ADDRESS);
							$("#SIM_ICCID").text(resp.packInfo.SIM_ICCID);
						//未关联厂区提示
						if(_packInfo.FAC_NAME==undefined){
							$("#FAC_NAME").text("尚未关联厂区").css({
								'color': 'red'
							});
						}
					}
					else {
						$("#packDetail").hide();
					}
					//App.unblockUI($("#packDetail"));//停止loading
				},
				error:function(e){
					//App.unblockUI($("#packDetail"));//停止loading
					rmsBox.notify('error', {msg: '出错了！',delay:3000});
				}
			});
		},
		/**
		 * 历史记录表格初始化 默认查询当天所有记录 查询条件为时间范围
		 * @param c 终端id
		 * @param p 电池唯一序列号
		 */
		historyDataTableInit:function(p,c){
			
	        //处理表格
			$('#pack_monitor_history_table').DataTable({
				"processing" : true,
				"serverSide" : true,
				"sAjaxSource" : "main/packDataMonitor/getMonitorHistoryDataList.mvc",
				"fnServerData" : queryData,
				"pageLength" : 10,
				"sDom" : "<'row-fluid'r>t<'row-fluid'<'span6'i><'span6'p>>",
				"oLanguage" : util.getDToLanguage(),
				"columns" : [ 
				{
					"data" : "",
					"bSortable" : false,
					"defaultContent": "",
					"visible":false
				},
				{
					"data" : "colClientId",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "packCode",
					"bSortable" : false,
					"defaultContent": ""
				},
				{
					"data" : "gatherTime",
					"bSortable" : false,
					"defaultContent": "",
					"render" : function(data, type, full, meta) {
						if(data){
							return '<a style="cursor:pointer;color:blue;" data-toggle="modal" onclick="history_data.showDetail(\''+util.getDateStr(full.gatherTime)+'\',\''+full.packCode+'\',\''+full.colClientId+'\')">'+util.getDateStr(data)+'</a>';
						}
					}
				}
			 ]
			});
			//table查询方法
			function queryData(sSource, aoData, fnCallback) {
				aoData.push({
					"name" : "packCode",
					"value" : p
				});
                aoData.push({
                    "name" : "colClientId",
                    "value" : c
                });
				aoData.push({
					"name" : "startTime",
					"value" : $("#startTime").val()
				});
				aoData.push({
					"name" : "endTime",
					"value" : $("#endTime").val()
				});
				$.ajax({
					"type" : "get",
					"contentType" : "application/json",
					"url" : sSource,
					"dataType" : "json",
					"data" : {
						"aoData" : JSON.stringify(aoData)
					},
					"success" : function(resp) {
						fnCallback(resp);
					}
				});
			};
		},
		//下载报文
		downloadDatagram : function(id) {
			var param = {};
			param['pkId'] = id;
			$.fileDownload("main/packDataMonitor/downloadDatagram.mvc", {
    			httpMethod: 'POST',
    			data: param,
    			prepareCallback:function(url){
    			},
    			successCallback:function(url){
    			},
    			failCallback: function (html, url) {
    				util.showModal("#_alertModal", "未找到指定文件，下载失败！");
    			}
            });
		},
		//数据回传
		dataBack : function (id) {
			var param = {};
			param['pkId'] = id;
			//加遮罩
			App.blockUI($("#tab_1_4"));
			$.ajax({
				"type" : "post",
				"url" : "main/packDataMonitor/dataBack.mvc",
				"dataType" : "json",
				"data" : param,
				"success" : function(resp) {
					App.unblockUI($("#tab_1_4"));
					if (resp.msg=='error') {
						rmsBox.notify('error', {msg: '数据异常，回传失败！'});
					} else if (resp.msg=='error dict') {
						rmsBox.notify('error', {msg: '系统相关配置数据错误，请系统管理员！', delay:'2500', width : '400px'});
					} else if (resp.msg=='FILE_EMPTY') {
						rmsBox.notify('error', {msg: '未找到报文文件！', delay:'2500', width : '400px'});
					} else {
						rmsBox.notify('success', {msg: '数据回传成功！'});
						var table = $('#history_warning_table').DataTable();
						table.draw(true);
					}
				},
				error:function(e){
					App.unblockUI($("#tab_1_4"));
					rmsBox.notify('error', {msg: '数据回传失败！'});
				}
			});
		},
		showClientInfoPanel:function(){
	    	$.ajax({
				"type" : "post",
				"url" : "main/sysUser/checkUserClass.mvc",
				"async" : false,
				"dataType":"json",
				"success" : function(resp) {
				    if(resp.flag == "false"){
				    	$("#client_panel_div").show();
				    } else {
				    	$("#client_panel_div").hide();
				    }
				}
	        });
	},
	
	/**
		 * 
		 * @param id 设置的id
		 * @param count 信号
		 */
		setSign:function(id, count){
			var tmpElement = document.getElementById(id);
			for(var i=0;i<5;i++){
				tmpElement.children[i].style.backgroundColor = "#FFF";
				if(i<=count-1){
					if(count<2){ 
						tmpElement.children[i].style.backgroundColor = "red";//一格时为红色
					}else{
						tmpElement.children[i].style.backgroundColor = "#00ABC5";
					}
				}
			}
		},
		/**
		 * 绘制温度仪表盘
		 * @param divId 温度仪表divId
		 * @param data 数据
		 */
		setTempCanvas:function(divId, tempData){
			var option = {
				    tooltip : {
				        formatter: "{a} <br/>{b} : {c}℃"
				    },
				    toolbox: {
				        show : true,
				        feature : {
				            mark : {show: true}
				        }
				    },
				    series : [
				        {   splitNumber:11,
				        	min:-30,
				        	max:80,
				        	axisLine: {            // 坐标轴线  
			                     lineStyle: {       // 属性lineStyle控制线条样式  
			                         color: [[0.27, '#93C8AC'], [0.82, '#6683A0'], [1, '#C3362F']]
			                                }  
			                            },   
				            name:'监测点最高温度',
				            type:'gauge',
				            detail : {formatter:'{value}℃'},
				            data:[{value: tempData, name: '温度'}]
				        }
				    ]
				};
		    var myChart = echarts.init(document.getElementById(divId));
		    myChart.setOption(option,true);
		},

        initPackCodeSelect: function(divId,selectWidth) {
            $("#"+divId).select2({
                language: "zh-CN",
                allowClear: true,
                width: selectWidth||"175px",
                placeholder: "请选择",
                ajax: {
                    url: "monitor/historyQuery/getPackCodeOptions2.mvc",
                    dataType: 'json',
                    delay: 250,
                    data: function(params) {
                        params.offset = 10;
                        params.page = params.page || 1;
                        return {
                            name: params.term,
                            page: params.page,
                            offset: params.offset
                        };
                    },
                    cache: false,
                    processResults: function(res, params) {
                        var users = res.data;
                        var options = [];
                        for (var i = 0, len = users.length; i < len; i++) {
                            var option = {
                                "id": users[i]["pkId"],
                                "text": (users[i]["serialNo"])
                            };
                            options.push(option);
                        }
                        return {
                            results: options,
                            pagination: {
                                more: (params.page * params.offset) < res.total
                            }
                        };
                    },
                    escapeMarkup: function(markup) {
                        return markup;
                    },
                    minimumInputLength: 1
                }
            });
        },
		
		/**
		 * 绘制电池soc canvas
		 * @param val soc percent
		 */
		setSocCanvas : function(val) {
			var canvas = document.getElementById('canvas'), ctx = canvas
					.getContext('2d');

			var width = 75, height = 20, max = 100;
			// Draw the background
			ctx.fillStyle = '#D2DDEB';
			ctx.clearRect(0, 0, canvas.width, canvas.height);
			ctx.fillRect(0, 0, width, height);
			// Draw the fill
			ctx.fillStyle = '#68CB68';
			var fillVal = Math.min(Math.max(val / max, 0), 1);
			ctx.fillRect(0, 0, fillVal * width, height);
			//添加百分比文字
			ctx.font = "30pt";
			ctx.strokeText(val + "%", 30, 15);
			ctx.strokeStyle = "black";
			ctx.stroke();
			//电池帽子
			ctx.fillStyle = '#D2DDEB';
			ctx.fillRect(75, 5, 6, 9);
		}
		
	};
}();